package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.TravelComment;
import cn.wolfcode.luowowo.query.TravelCommentQuery;
import cn.wolfcode.luowowo.repository.TravelCommentRepository;
import cn.wolfcode.luowowo.service.ITravelCommentService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class TravelCommentServiceImpl implements ITravelCommentService {

    @Autowired
    private TravelCommentRepository travelCommentRepository;

    @Autowired
    private MongoTemplate template;



    @Override
    public TravelComment get(String id) {
        return travelCommentRepository.findById(id).orElse(null);
    }


    @Override
    public List<TravelComment> list() {
        return travelCommentRepository.findAll();
    }

    @Override
    public void save(TravelComment travelComment) {
        travelComment.setId(null);
        travelCommentRepository.save(travelComment);
    }


    @Override
    public void delete(String id) {
        travelCommentRepository.deleteById(id);
    }

    @Override
    public Page<TravelComment> query(TravelCommentQuery qo) {
        // 查询条件
        Query query = new Query();

        if (StringUtils.hasLength(qo.getTravelId())) {
            query.addCriteria(Criteria.where("travelId").is(qo.getTravelId()));
        }

        // 拼接高级查询条件
        if (StringUtils.hasLength(qo.getKeyword())) {
            query.addCriteria(Criteria.where("name").regex(".*"+qo.getKeyword()+".*"));
        }

        // 列表数据
        PageRequest request = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, "_id");

        return DBHelper.query(template,TravelComment.class,query,request);
    }

    @Override
    public void commentAdd(TravelComment comment) {
        comment.setCreateTime(new Date());
        // 如果评论里边包含评论,说明是评论的评论
        if (StringUtils.hasLength(comment.getRefComment().getId())){
            // 处理
            comment.setType(comment.TRAVLE_COMMENT_TYPE);   // 评论类型改为 1,表示评论的评论
            // 获取评论对象
            TravelComment travelComment = this.get(comment.getRefComment().getId());
            // 设置给当前评论对象的 RefComment属性
            comment.setRefComment(travelComment);
        }

        this.save(comment);
    }

    @Override
    public List<TravelComment> comments(String travelId) {
        List<TravelComment> travelComments = travelCommentRepository.findByTravelId(travelId);
        return travelComments;
    }


}
